import Bus from "@/utils/eventBus"
import { ElMessage } from 'element-plus'
export default class SocketService {
    static instance:any = null;
    static get Instance() {
        if (!this.instance) {
            this.instance = new SocketService();
        }
        return this.instance;
    }
    // 和服务端连接的socket对象
    ws:any = null;
    // 存储回调函数
    callBackMapping:any = {};
    // 标识是否连接成功
    connected:any = false;
    // 记录重试的次数
    sendRetryCount:any = 0;
    // 重新连接尝试的次数
    connectRetryCount:any = 0;
    //  定义连接服务器的方法
    connect() {
        // 连接服务器
        if (!window.WebSocket) {
            return console.log('您的浏览器不支持WebSocket');
        }
        // let token = $.cookie('123');
        // let token = '4E6EF539AAF119D82AC4C2BC84FBA21F';
        let url = 'ws://39.101.197.161:1234';
        this.ws = new WebSocket(url);
        // 连接成功的事件
        this.ws.onopen = () => {
            console.log('连接服务端成功了');
            this.connected = true;
            // 重置重新连接的次数
            this.connectRetryCount = 0;
        };
        // 1.连接服务端失败
        // 2.当连接成功之后, 服务器关闭的情况
        this.ws.onclose = () => {
            console.log('连接服务端失败');
            this.connected = false;
            this.connectRetryCount++;
            setTimeout(() => {
                this.connect();
            }, 500 * this.connectRetryCount);
        };
        // 得到服务端发送过来的数据
        this.ws.onmessage = (msg:any) => {
            let  msgData = JSON.parse(msg.data);
            if(msgData.action){
                ElMessage({
                    type: msgData.action!='finish'?'warning':'success',
                    message: msgData.content,
                    duration:5000,
                    showClose:true
                })
                // Bus.$emit(`socket_${msgData.action}`,msgData)
                Bus.$emit(`openEmergencyDetail`,msgData.params)
            }
            console.log(msgData, '从服务端获取到了数据');
        };
    }
    // 回调函数的注册
    registerCallBack(socketType:any, callBack:any) {
        this.callBackMapping[socketType] = callBack;
    }
    // 取消某一个回调函数
    unRegisterCallBack(socketType:any) {
        this.callBackMapping[socketType] = null;
    }
    // 发送数据的方法
    send(data:any) {
        // 判断此时此刻有没有连接成功
        if (this.connected) {
            this.sendRetryCount = 0;
            try {
                this.ws.send(JSON.stringify(data));
            } catch (e) {
                this.ws.send(data);
            }
        } else {
            this.sendRetryCount++;
            setTimeout(() => {
                this.send(data);
            }, this.sendRetryCount * 500);
        }
    }
}
